package com.soujiayi.net;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.soujiayi.activity.MyApplication;
import com.soujiayi.model.Category;
import com.soujiayi.model.Categorys;
import com.soujiayi.model.Mall;
import com.soujiayi.model.Product;
import com.soujiayi.model.ProductCompare;
import com.soujiayi.model.ProductSelectItem;
import com.soujiayi.model.Products;
import com.soujiayi.model.SystemInfo;
import com.soujiayi.model.TuanCity;
import com.soujiayi.model.TuanMain;
import com.soujiayi.model.TuanMains;
import com.soujiayi.store.SPResolver;
import com.soujiayi.util.Constants;
import com.soujiayi.util.Encryptor;
import com.soujiayi.util.SystemInfoUtil;
import com.soujiayi.weibo.User;
import com.sun.mail.iap.ByteArray;

public class HttpRequester {

	private ExecutorService executorService;
	private Handler handler;
	private Context context;
	private final static int CONNECT_TIME_OUT = 20000;
	private final static int READ_TIME_OUT = 40000;

	public HttpRequester(Context context) {
		this.context = context;
	}

	public Handler getHandler() {
		return handler;
	}

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	public HttpRequester(Context context, int threadNumber, Handler handler) {
		this.context = context;
		executorService = Executors.newFixedThreadPool(threadNumber);
		this.handler = handler;
	}

	public void searchGoods(final Map<String, String> parameters) {
		executorService.submit(new Runnable() {
			@Override
			public void run() {

				String result = executeGet(HttpURLEncode(
						Constants.GOODS_SEARCH, parameters));
				if (result == null) {
					return;
				}
				if (result.indexOf("\"status\":\"NORMAL\"") < 0
						&& result.indexOf("\"status\":\"NOT_FOUND_RECOREDS\"") < 0) {
					Message msg = new Message();
					Bundle bundle = new Bundle();
					bundle.putBoolean(Constants.IS_ERROR, true);
					msg.setData(bundle);
					handler.sendMessage(msg);
					return;
				}
				result = result.replace("[]", "{}");
				result = result.replace("\"mallsupport\":{}",
						"\"mallsupport\":[]");
				Products products = new Products();
				try {
					JSONObject resultJson = new JSONObject(result);

					JSONObject data = resultJson.getJSONObject("data");
					if (!data.isNull("total")) {
						int total = data.getInt("total");
						products.setTotal(total);
					}
					if (!data.isNull("total_found")) {
						int total_found = data.getInt("total_found");
						products.setTotal_found(total_found);
					}
					if (!data.isNull("minprice")) {
						float minprice = Float.parseFloat(data
								.getString("minprice"));
						products.setMinprice(minprice);
					}
					if (!data.isNull("maxprice")) {
						float maxprice = Float.parseFloat(data
								.getString("maxprice"));
						products.setMaxprice(maxprice);
					}

					// 鍟嗗搧鍒楄〃
					JSONObject list = data.getJSONObject("list");
					Iterator<String> keys = list.keys();
					List<Product> productlist = new ArrayList<Product>();
					while (keys.hasNext()) {
						String key = keys.next();
						JSONObject productJSON = list.getJSONObject(key);
						Product product = new Product();
						if (!productJSON.isNull("detailurl")) {
							String detailurl = productJSON
									.getString("detailurl");
							product.setDetailurl(detailurl);
						}
						if (!productJSON.isNull("goodsid")) {
							String goodsid = productJSON.getString("goodsid");
							product.setGoodsid(goodsid);
						}
						if (!productJSON.isNull("name")) {
							String name = productJSON.getString("name");
							product.setName(name);
						}
						if (!productJSON.isNull("cover")) {
							String cover = productJSON.getString("cover");
							product.setCover(cover);
						}
						if (!productJSON.isNull("saleprice")) {
							String saleprice = productJSON
									.getString("saleprice");
							product.setSaleprice(saleprice);
						}
						if (!productJSON.isNull("saleprice_isup")) {
							int saleprice_isup = productJSON
									.getInt("saleprice_isup");
							product.setSaleprice_isup(saleprice_isup);
						}
						if (!productJSON.isNull("mallid")) {
							String mallid = productJSON.getString("mallid");
							product.setMallid(mallid);
						}
						if (!productJSON.isNull("mallname")) {
							String mallname = productJSON.getString("mallname");
							product.setMallname(mallname);
						}
						if (!productJSON.isNull("mallsupport")) {
							List<String> mallsupport = new ArrayList<String>();
							JSONArray mallsupportList = productJSON
									.getJSONArray("mallsupport");
							for (int i = 0; i < mallsupportList.length(); i++) {
								mallsupport.add(mallsupportList.getString(i));
							}
							product.setMallsupport(mallsupport);
						}
						if (!productJSON.isNull("brandid")) {
							String brandid = productJSON.getString("brandid");
							product.setBrandid(brandid);
						}
						if (!productJSON.isNull("brandname")) {
							String brandname = productJSON
									.getString("brandname");
							if (brandname.equals("null")) {
								brandname = null;
							}
							product.setBrandname(brandname);
						}
						if (!productJSON.isNull("catid")) {
							String catid = productJSON.getString("catid");
							product.setCatid(catid);
						}
						if (!productJSON.isNull("catname")) {
							String catname = productJSON.getString("catname");
							product.setCatname(catname);
						}
						if (!productJSON.isNull("detailurl")) {
							String detailurl = productJSON
									.getString("detailurl");
							product.setDetailurl(detailurl);
						}
						if (!productJSON.isNull("buyurl")) {
							String buyurl = productJSON.getString("buyurl");
							product.setBuyurl(buyurl);
						}

						// 姣斾环淇℃伅
						if (!productJSON.isNull("compare")) {
							ProductCompare compare = new ProductCompare();
							JSONObject compareJSON = productJSON
									.getJSONObject("compare");
							if (!compareJSON.isNull("goodsnum")) {
								int goodsnum = compareJSON.getInt("goodsnum");
								compare.setGoodsnum(goodsnum);
							}
							if (!compareJSON.isNull("mallnum")) {
								int mallnum = compareJSON.getInt("mallnum");
								compare.setMallnum(mallnum);
							}
							if (!compareJSON.isNull("minprice")) {
								float minprice = Float.parseFloat(compareJSON
										.getString("minprice"));
								compare.setMinprice(minprice);
							}
							if (!compareJSON.isNull("maxprice")) {
								float maxprice = Float.parseFloat(compareJSON
										.getString("maxprice"));
								compare.setMaxprice(maxprice);
							}

							// 姣斾环鍟嗗煄
							if (!compareJSON.isNull("mall")) {
								JSONObject malllistJSON = compareJSON
										.getJSONObject("mall");
								Iterator<String> malllistkeys = malllistJSON
										.keys();
								List<Mall> malls = new ArrayList<Mall>();
								while (malllistkeys.hasNext()) {
									String mallkey = malllistkeys.next();
									JSONObject comparemallJSON = malllistJSON
											.getJSONObject(mallkey);
									Mall comparemall = new Mall();
									if (!comparemallJSON.isNull("mallid")) {
										String mallid = comparemallJSON
												.getString("mallid");
										comparemall.setMallid(mallid);
									}
									if (!comparemallJSON.isNull("mallname")) {
										String mallname = comparemallJSON
												.getString("mallname");
										comparemall.setMallname(mallname);
									}
									if (!comparemallJSON
											.isNull("mall_detailurl")) {
										String mall_detailurl = comparemallJSON
												.getString("mall_detailurl");
										comparemall
												.setMall_detailurl(mall_detailurl);
									}
									if (!comparemallJSON.isNull("mall_buyurl")) {
										String mall_buyurl = comparemallJSON
												.getString("mall_buyurl");
										comparemall.setMall_buyurl(mall_buyurl);
									}
									if (!comparemallJSON.isNull("goodsid")) {
										String goodsid = comparemallJSON
												.getString("goodsid");
										comparemall.setGoodsid(goodsid);
									}
									if (!comparemallJSON.isNull("detailurl")) {
										String detailurl = comparemallJSON
												.getString("detailurl");
										comparemall.setDetailurl(detailurl);
									}
									if (!comparemallJSON.isNull("buyurl")) {
										String buyurl = comparemallJSON
												.getString("buyurl");
										comparemall.setBuyurl(buyurl);
									}
									if (!comparemallJSON.isNull("price")) {
										float price = Float
												.parseFloat(comparemallJSON
														.getString("price"));
										comparemall.setPrice(price);
									}
									malls.add(comparemall);
								}
								compare.setMalls(malls);
							}
							product.setCompare(compare);
						}
						productlist.add(product);
					}
					products.setProductlist(productlist);

					// 鎼滅储缁撴灉鎵€灞炵殑鍒嗙被
					if (!data.isNull("catlist")) {
						JSONObject catlistJSON = data.getJSONObject("catlist");
						Iterator<String> catlistkeys = catlistJSON.keys();
						ArrayList<ProductSelectItem> catlist = new ArrayList<ProductSelectItem>();
						while (catlistkeys.hasNext()) {
							String catlistkey = catlistkeys.next();
							JSONObject catJSON = catlistJSON
									.getJSONObject(catlistkey);
							ProductSelectItem cat = new ProductSelectItem();
							if (!catJSON.isNull("catid")) {
								String catid = catJSON.getString("catid");
								cat.setId(catid);
							}
							if (!catJSON.isNull("name")) {
								String name = catJSON.getString("name");
								cat.setName(name);
							}
							if (!catJSON.isNull("total")) {
								int total = catJSON.getInt("total");
								cat.setTotal(total);
							}
							catlist.add(cat);
						}
						products.setCatlist(catlist);
					}

					// 鎼滅储缁撴灉鎵€灞炵殑鍟嗗煄
					if (!data.isNull("malllist")) {
						JSONObject malllistJSON = data
								.getJSONObject("malllist");
						Iterator<String> malllistkeys = malllistJSON.keys();
						ArrayList<ProductSelectItem> malllist = new ArrayList<ProductSelectItem>();
						while (malllistkeys.hasNext()) {
							String malllistkey = malllistkeys.next();
							JSONObject mallJSON = malllistJSON
									.getJSONObject(malllistkey);
							ProductSelectItem mall = new ProductSelectItem();
							if (!mallJSON.isNull("mallid")) {
								String mallid = mallJSON.getString("mallid");
								mall.setId(mallid);
							}
							if (!mallJSON.isNull("name")) {
								String mallname = mallJSON.getString("name");
								mall.setName(mallname);
							}
							if (!mallJSON.isNull("total")) {
								int total = mallJSON.getInt("total");
								mall.setTotal(total);
							}
							malllist.add(mall);
						}
						products.setMalllist(malllist);
					}

					// 鎼滅储缁撴灉鎵€灞炵殑鍝佺墝
					if (!data.isNull("brandlist")) {
						JSONObject brandlistJSON = data
								.getJSONObject("brandlist");
						Iterator<String> brandlistkeys = brandlistJSON.keys();
						ArrayList<ProductSelectItem> brandlist = new ArrayList<ProductSelectItem>();
						while (brandlistkeys.hasNext()) {
							String brandlistkey = brandlistkeys.next();
							JSONObject brandJSON = brandlistJSON
									.getJSONObject(brandlistkey);
							ProductSelectItem brand = new ProductSelectItem();
							if (!brandJSON.isNull("brandid")) {
								String brandid = brandJSON.getString("brandid");
								brand.setId(brandid);
							}
							if (!brandJSON.isNull("name")) {
								String name = brandJSON.getString("name");
								brand.setName(name);
							}
							if (!brandJSON.isNull("total")) {
								int total = brandJSON.getInt("total");
								brand.setTotal(total);
							}
							brandlist.add(brand);
						}
						products.setBrandlist(brandlist);
					}

					// 鎼滅储缁撴灉鎵€灞炵殑浜岀骇鍒嗙被
					if (!data.isNull("subcatlist")) {
						JSONObject subcatlistJSON = data
								.getJSONObject("subcatlist");
						Iterator<String> subcatlistkeys = subcatlistJSON.keys();
						ArrayList<ProductSelectItem> sbucatlist = new ArrayList<ProductSelectItem>();
						while (subcatlistkeys.hasNext()) {
							String subcatlistkey = subcatlistkeys.next();
							JSONObject subcatJSON = subcatlistJSON
									.getJSONObject(subcatlistkey);
							ProductSelectItem subcat = new ProductSelectItem();
							if (!subcatJSON.isNull("catid")) {
								String catid = subcatJSON.getString("catid");
								subcat.setId(catid);
							}
							if (!subcatJSON.isNull("name")) {
								String name = subcatJSON.getString("name");
								subcat.setName(name);
							}
							if (!subcatJSON.isNull("total")) {
								int total = subcatJSON.getInt("total");
								subcat.setTotal(total);
							}
							sbucatlist.add(subcat);
						}
						products.setCatlist(sbucatlist);
					}

					// 鎼滅储缁撴灉鎵€灞炵殑灞炴€�
					if (!data.isNull("attrlist")) {
						JSONObject attrlistJSON = data
								.getJSONObject("attrlist");
						Iterator<String> attrlistkeys = attrlistJSON.keys();
						ArrayList<ProductSelectItem> attrlist = new ArrayList<ProductSelectItem>();
						while (attrlistkeys.hasNext()) {
							String attrlistkey = attrlistkeys.next();
							JSONObject attrJSON = attrlistJSON
									.getJSONObject(attrlistkey);
							ProductSelectItem attr = new ProductSelectItem();
							if (!attrJSON.isNull("attrid")) {
								String attrid = attrJSON.getString("attrid");
								attr.setId(attrid);
							}
							if (!attrJSON.isNull("name")) {
								String name = attrJSON.getString("name");
								attr.setName(name);
							}
							if (!attrJSON.isNull("total")) {
								int total = attrJSON.getInt("total");
								attr.setTotal(total);
							}
							attrlist.add(attr);
						}
						products.setAttrlist(attrlist);
					}

				} catch (JSONException e) {
					System.out.println(e);
				}

				Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putSerializable(Constants.PRODUCTS, products);
				msg.setData(bundle);
				handler.sendMessage(msg);

			}
		});

	}

	public void getGoodsDetail(final Map<String, String> parameters) {
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				Product product = new Product();
				try {
					String result = executeGet(HttpURLEncode(
							Constants.GOODS_DETAIL, parameters));
					if (result == null) {
						return;
					}
					if (result.indexOf("\"status\":\"NORMAL\"") < 0
							&& result
									.indexOf("\"status\":\"NOT_FOUND_RECOREDS\"") < 0) {
						Message msg = new Message();
						Bundle bundle = new Bundle();
						bundle.putBoolean(Constants.IS_ERROR, true);
						msg.setData(bundle);
						handler.sendMessage(msg);
						return;
					}

					result = result.replace("[]", "{}");
					result = result.replace("\"mallsupport\":{}",
							"\"mallsupport\":[]");

					JSONObject resultJson = new JSONObject(result);

					JSONObject productJSON = resultJson.getJSONObject("data");

					if (!productJSON.isNull("goodsid")) {
						String goodsid = productJSON.getString("goodsid");
						product.setGoodsid(goodsid.equals("null") ? null
								: goodsid);
					}
					if (!productJSON.isNull("name")) {
						String name = productJSON.getString("name");
						product.setName(name.equals("null") ? null : name);
					}
					if (!productJSON.isNull("saleprice")) {
						String saleprice = productJSON.getString("saleprice");
						product.setSaleprice(saleprice.equals("null") ? null
								: saleprice);
					}
					if (!productJSON.isNull("saleprice_isup")) {
						int saleprice_isup = productJSON
								.getInt("saleprice_isup");
						product.setSaleprice_isup(saleprice_isup);
					}
					if (!productJSON.isNull("cover")) {
						String cover = productJSON.getString("cover");
						product.setCover(cover.equals("null") ? null : cover);
					}
					if (!productJSON.isNull("reviews")) {
						int reviews = Integer.parseInt(productJSON
								.getString("reviews"));
						product.setReviews(reviews);
					}
					if (!productJSON.isNull("reviewscore")) {
						float reviewscore = Float
								.parseFloat(productJSON
										.getString("reviewscore")
										.equals("null") ? "0.0" : productJSON
										.getString("reviewscore"));
						product.setReviewscore(reviewscore);
					}
					if (!productJSON.isNull("attr")) {
						JSONObject attrsJSON = productJSON
								.getJSONObject("attr");
						Iterator<String> attrkeys = attrsJSON.keys();
						ArrayList<ProductSelectItem> attrlist = new ArrayList<ProductSelectItem>();
						while (attrkeys.hasNext()) {
							String attrkey = attrkeys.next();
							ProductSelectItem attr = new ProductSelectItem();
							if (!attrsJSON.isNull(attrkey)) {
								attr.setName(attrkey);
								attr.setValue(attrsJSON.getString(attrkey));
								attrlist.add(attr);
							}
						}
						product.setAttr(attrlist);
					}
					if (!productJSON.isNull("description")) {
						String description = productJSON
								.getString("description");
						product.setDescription(description.equals("null") ? null
								: description);
					}
					if (!productJSON.isNull("mallid")) {
						String mallid = productJSON.getString("mallid");
						product.setMallid(mallid.equals("null") ? null : mallid);
					}
					if (!productJSON.isNull("mallname")) {
						String mallname = productJSON.getString("mallname");
						product.setMallname(mallname.equals("null") ? null
								: mallname);
					}
					if (!productJSON.isNull("mallsupport")) {
						List<String> mallsupport = new ArrayList<String>();
						JSONArray mallsupportList = productJSON
								.getJSONArray("mallsupport");
						for (int i = 0; i < mallsupportList.length(); i++) {
							mallsupport.add(mallsupportList.getString(i));
						}
						product.setMallsupport(mallsupport);
					}
					if (!productJSON.isNull("mall_detailurl")) {
						String mall_detailurl = productJSON
								.getString("mall_detailurl");
						product.setMall_detailurl(mall_detailurl.equals("null") ? null
								: mall_detailurl);
					}
					if (!productJSON.isNull("mall_buyurl")) {
						String mall_buyurl = productJSON
								.getString("mall_buyurl");
						product.setMall_buyurl(mall_buyurl.equals("null") ? null
								: mall_buyurl);
					}
					if (!productJSON.isNull("catid")) {
						String catid = productJSON.getString("catid");
						product.setCatid(catid.equals("null") ? null : catid);
					}
					if (!productJSON.isNull("catname")) {
						String catname = productJSON.getString("catname");
						product.setCatname(catname.equals("null") ? null
								: catname);
					}
					if (!productJSON.isNull("brandid")) {
						String brandid = productJSON.getString("brandid");
						product.setBrandid(brandid.equals("null") ? null
								: brandid);
					}
					if (!productJSON.isNull("brandname")) {
						String brandname = productJSON.getString("brandname");
						product.setBrandname(brandname.equals("null") ? null
								: brandname);
					}
					if (!productJSON.isNull("detailurl")) {
						String detailurl = productJSON.getString("detailurl");
						product.setDetailurl(detailurl.equals("null") ? null
								: detailurl);
					}
					if (!productJSON.isNull("buyurl")) {
						String buyurl = productJSON.getString("buyurl");
						product.setBuyurl(buyurl.equals("null") ? null : buyurl);
					}

					// 姣斾环淇℃伅
					if (!productJSON.isNull("comparemall")) {
						ProductCompare compare = new ProductCompare();
						JSONObject compareMallJSON = productJSON
								.getJSONObject("comparemall");
						if (!compareMallJSON.isNull("goodsnum")) {
							int goodsnum = compareMallJSON.getInt("goodsnum");
							compare.setGoodsnum(goodsnum);
						}
						if (!compareMallJSON.isNull("mallnum")) {
							int mallnum = compareMallJSON.getInt("mallnum");
							compare.setMallnum(mallnum);
						}
						if (!compareMallJSON.isNull("minprice")) {
							float minprice = Float.parseFloat(compareMallJSON
									.getString("minprice"));
							compare.setMinprice(minprice);
						}
						if (!compareMallJSON.isNull("maxprice")) {
							float maxprice = Float.parseFloat(compareMallJSON
									.getString("maxprice"));
							compare.setMaxprice(maxprice);
						}

						// 姣斾环鍟嗗煄
						if (!compareMallJSON.isNull("mall")) {
							JSONObject malllistJSON = compareMallJSON
									.getJSONObject("mall");
							Iterator<String> malllistkeys = malllistJSON.keys();
							List<Mall> malls = new ArrayList<Mall>();
							while (malllistkeys.hasNext()) {
								String mallkey = malllistkeys.next();
								JSONObject comparemallJSON = malllistJSON
										.getJSONObject(mallkey);
								Mall comparemall = new Mall();
								if (!comparemallJSON.isNull("mallid")) {
									String mallid = comparemallJSON
											.getString("mallid");
									comparemall.setMallid(mallid.equals("null") ? null
											: mallid);
								}
								if (!comparemallJSON.isNull("mallname")) {
									String mallname = comparemallJSON
											.getString("mallname");
									comparemall.setMallname(mallname
											.equals("null") ? null : mallname);
								}
								if (!comparemallJSON.isNull("mall_detailurl")) {
									String mall_detailurl = comparemallJSON
											.getString("mall_detailurl");
									comparemall
											.setMall_detailurl(mall_detailurl
													.equals("null") ? null
													: mall_detailurl);
								}
								if (!comparemallJSON.isNull("mall_buyurl")) {
									String mall_buyurl = comparemallJSON
											.getString("mall_buyurl");
									comparemall.setMall_buyurl(mall_buyurl
											.equals("null") ? null
											: mall_buyurl);
								}
								if (!comparemallJSON.isNull("goodsid")) {
									String goodsid = comparemallJSON
											.getString("goodsid");
									comparemall.setGoodsid(goodsid
											.equals("null") ? null : goodsid);
								}
								if (!comparemallJSON.isNull("detailurl")) {
									String detailurl = comparemallJSON
											.getString("detailurl");
									comparemall.setDetailurl(detailurl
											.equals("null") ? null : detailurl);
								}
								if (!comparemallJSON.isNull("buyurl")) {
									String buyurl = comparemallJSON
											.getString("buyurl");
									comparemall.setBuyurl(buyurl.equals("null") ? null
											: buyurl);
								}
								if (!comparemallJSON.isNull("price")) {
									float price = Float
											.parseFloat(comparemallJSON
													.getString("price"));
									comparemall.setPrice(price);
								}
								malls.add(comparemall);
							}
							compare.setMalls(malls);
						}
						product.setCompare(compare);
					}

				} catch (JSONException e) {
					System.out.println(e);
				}

				Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putSerializable(Constants.PRODUCT, product);
				msg.setData(bundle);
				handler.sendMessage(msg);

			}
		});
	}

	public Product getGoodsDetailForFav(final Map<String, String> parameters)
			throws JSONException {
		Product product = new Product();
		String result = executeGet(HttpURLEncode(Constants.GOODS_DETAIL,
				parameters));
		if (result == null) {
			return null;
		}
		if (result.indexOf("\"status\":\"NORMAL\"") < 0
				&& result.indexOf("\"status\":\"NOT_FOUND_RECOREDS\"") < 0) {
			Message msg = new Message();
			Bundle bundle = new Bundle();
			bundle.putBoolean(Constants.IS_ERROR, true);
			msg.setData(bundle);
			handler.sendMessage(msg);
			return null;
		}

		result = result.replace("[]", "{}");
		result = result.replace("\"mallsupport\":{}", "\"mallsupport\":[]");

		JSONObject resultJson = new JSONObject(result);

		JSONObject productJSON = resultJson.getJSONObject("data");

		if (!productJSON.isNull("goodsid")) {
			String goodsid = productJSON.getString("goodsid");
			product.setGoodsid(goodsid.equals("null") ? null : goodsid);
		}
		if (!productJSON.isNull("name")) {
			String name = productJSON.getString("name");
			product.setName(name.equals("null") ? null : name);
		}
		if (!productJSON.isNull("saleprice")) {
			String saleprice = productJSON.getString("saleprice");
			product.setSaleprice(saleprice.equals("null") ? null : saleprice);
		}
		if (!productJSON.isNull("saleprice_isup")) {
			int saleprice_isup = productJSON.getInt("saleprice_isup");
			product.setSaleprice_isup(saleprice_isup);
		}
		if (!productJSON.isNull("cover")) {
			String cover = productJSON.getString("cover");
			product.setCover(cover.equals("null") ? null : cover);
		}
		if (!productJSON.isNull("reviews")) {
			int reviews = Integer.parseInt(productJSON.getString("reviews"));
			product.setReviews(reviews);
		}
		if (!productJSON.isNull("reviewscore")) {
			float reviewscore = Float.parseFloat(productJSON.getString(
					"reviewscore").equals("null") ? "0.0" : productJSON
					.getString("reviewscore"));
			product.setReviewscore(reviewscore);
		}
		if (!productJSON.isNull("attr")) {
			JSONObject attrsJSON = productJSON.getJSONObject("attr");
			Iterator<String> attrkeys = attrsJSON.keys();
			ArrayList<ProductSelectItem> attrlist = new ArrayList<ProductSelectItem>();
			while (attrkeys.hasNext()) {
				String attrkey = attrkeys.next();
				ProductSelectItem attr = new ProductSelectItem();
				if (!attrsJSON.isNull(attrkey)) {
					attr.setName(attrkey);
					attr.setValue(attrsJSON.getString(attrkey));
					attrlist.add(attr);
				}
			}
			product.setAttr(attrlist);
		}
		if (!productJSON.isNull("description")) {
			String description = productJSON.getString("description");
			product.setDescription(description.equals("null") ? null
					: description);
		}
		if (!productJSON.isNull("mallid")) {
			String mallid = productJSON.getString("mallid");
			product.setMallid(mallid.equals("null") ? null : mallid);
		}
		if (!productJSON.isNull("mallname")) {
			String mallname = productJSON.getString("mallname");
			product.setMallname(mallname.equals("null") ? null : mallname);
		}
		if (!productJSON.isNull("mallsupport")) {
			List<String> mallsupport = new ArrayList<String>();
			JSONArray mallsupportList = productJSON.getJSONArray("mallsupport");
			for (int i = 0; i < mallsupportList.length(); i++) {
				mallsupport.add(mallsupportList.getString(i));
			}
			product.setMallsupport(mallsupport);
		}
		if (!productJSON.isNull("mall_detailurl")) {
			String mall_detailurl = productJSON.getString("mall_detailurl");
			product.setMall_detailurl(mall_detailurl.equals("null") ? null
					: mall_detailurl);
		}
		if (!productJSON.isNull("mall_buyurl")) {
			String mall_buyurl = productJSON.getString("mall_buyurl");
			product.setMall_buyurl(mall_buyurl.equals("null") ? null
					: mall_buyurl);
		}
		if (!productJSON.isNull("catid")) {
			String catid = productJSON.getString("catid");
			product.setCatid(catid.equals("null") ? null : catid);
		}
		if (!productJSON.isNull("catname")) {
			String catname = productJSON.getString("catname");
			product.setCatname(catname.equals("null") ? null : catname);
		}
		if (!productJSON.isNull("brandid")) {
			String brandid = productJSON.getString("brandid");
			product.setBrandid(brandid.equals("null") ? null : brandid);
		}
		if (!productJSON.isNull("brandname")) {
			String brandname = productJSON.getString("brandname");
			product.setBrandname(brandname.equals("null") ? null : brandname);
		}
		if (!productJSON.isNull("detailurl")) {
			String detailurl = productJSON.getString("detailurl");
			product.setDetailurl(detailurl.equals("null") ? null : detailurl);
		}
		if (!productJSON.isNull("buyurl")) {
			String buyurl = productJSON.getString("buyurl");
			product.setBuyurl(buyurl.equals("null") ? null : buyurl);
		}

		// 姣斾环淇℃伅
		if (!productJSON.isNull("comparemall")) {
			ProductCompare compare = new ProductCompare();
			JSONObject compareMallJSON = productJSON
					.getJSONObject("comparemall");
			if (!compareMallJSON.isNull("goodsnum")) {
				int goodsnum = compareMallJSON.getInt("goodsnum");
				compare.setGoodsnum(goodsnum);
			}
			if (!compareMallJSON.isNull("mallnum")) {
				int mallnum = compareMallJSON.getInt("mallnum");
				compare.setMallnum(mallnum);
			}
			if (!compareMallJSON.isNull("minprice")) {
				float minprice = Float.parseFloat(compareMallJSON
						.getString("minprice"));
				compare.setMinprice(minprice);
			}
			if (!compareMallJSON.isNull("maxprice")) {
				float maxprice = Float.parseFloat(compareMallJSON
						.getString("maxprice"));
				compare.setMaxprice(maxprice);
			}

			// 姣斾环鍟嗗煄
			if (!compareMallJSON.isNull("mall")) {
				JSONObject malllistJSON = compareMallJSON.getJSONObject("mall");
				Iterator<String> malllistkeys = malllistJSON.keys();
				List<Mall> malls = new ArrayList<Mall>();
				while (malllistkeys.hasNext()) {
					String mallkey = malllistkeys.next();
					JSONObject comparemallJSON = malllistJSON
							.getJSONObject(mallkey);
					Mall comparemall = new Mall();
					if (!comparemallJSON.isNull("mallid")) {
						String mallid = comparemallJSON.getString("mallid");
						comparemall.setMallid(mallid.equals("null") ? null
								: mallid);
					}
					if (!comparemallJSON.isNull("mallname")) {
						String mallname = comparemallJSON.getString("mallname");
						comparemall.setMallname(mallname.equals("null") ? null
								: mallname);
					}
					if (!comparemallJSON.isNull("mall_detailurl")) {
						String mall_detailurl = comparemallJSON
								.getString("mall_detailurl");
						comparemall.setMall_detailurl(mall_detailurl
								.equals("null") ? null : mall_detailurl);
					}
					if (!comparemallJSON.isNull("mall_buyurl")) {
						String mall_buyurl = comparemallJSON
								.getString("mall_buyurl");
						comparemall
								.setMall_buyurl(mall_buyurl.equals("null") ? null
										: mall_buyurl);
					}
					if (!comparemallJSON.isNull("goodsid")) {
						String goodsid = comparemallJSON.getString("goodsid");
						comparemall.setGoodsid(goodsid.equals("null") ? null
								: goodsid);
					}
					if (!comparemallJSON.isNull("detailurl")) {
						String detailurl = comparemallJSON
								.getString("detailurl");
						comparemall
								.setDetailurl(detailurl.equals("null") ? null
										: detailurl);
					}
					if (!comparemallJSON.isNull("buyurl")) {
						String buyurl = comparemallJSON.getString("buyurl");
						comparemall.setBuyurl(buyurl.equals("null") ? null
								: buyurl);
					}
					if (!comparemallJSON.isNull("price")) {
						float price = Float.parseFloat(comparemallJSON
								.getString("price"));
						comparemall.setPrice(price);
					}
					malls.add(comparemall);
				}
				compare.setMalls(malls);
			}
			product.setCompare(compare);
		}
		return product;

	}

	public void getGoodsCategory(final String sid, final String pid,
			final int type) {
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				HashMap<String, String> parameters = new HashMap<String, String>();
				parameters.put("pid", pid);

				if (sid == null || "".equals(sid)) {
					parameters.put("sid", getSessionId());
				} else
					parameters.put("sid", sid);
				String result = executeGet(HttpURLEncode(
						Constants.GOODS_CATEGORY, parameters));
				if (result == null) {
					return;
				}
				if (result.indexOf("\"status\":\"NORMAL\"") < 0
						&& result.indexOf("\"status\":\"NOT_FOUND_RECOREDS\"") < 0) {
					Message msg = new Message();
					Bundle bundle = new Bundle();
					bundle.putBoolean(Constants.IS_ERROR, true);
					msg.setData(bundle);
					handler.sendMessage(msg);
					return;
				}

				Categorys categorys = convertJSONStringToCategorys(result);
				Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putSerializable(Constants.CATEGORYS, categorys);
				bundle.putInt(Constants.CATEGORYS_TYPE, type);
				msg.setData(bundle);
				handler.sendMessage(msg);
			}
		});
	}

	private Categorys convertJSONStringToCategorys(String result) {
		Categorys categorys = new Categorys();
		try {
			JSONObject resultJson = new JSONObject(result);
			JSONObject itemsJson = resultJson.getJSONObject("items");
			Iterator<String> keys = itemsJson.keys();
			List<Category> categorylist = new ArrayList<Category>();
			while (keys.hasNext()) {
				String key = keys.next();
				JSONObject categoryJSON = itemsJson.getJSONObject(key);
				Category category = new Category();
				if (!categoryJSON.isNull("catid")) {
					String catid = categoryJSON.getString("catid");
					category.setCatid(catid);
				}
				if (!categoryJSON.isNull("firstchar")) {
					String firstchar = categoryJSON.getString("firstchar");
					category.setFirstchar(firstchar);
				}
				if (!categoryJSON.isNull("name")) {
					String name = categoryJSON.getString("name");
					category.setName(name);
				}
				if (!categoryJSON.isNull("parentid")) {
					String parentid = categoryJSON.getString("parentid");
					category.setParentid(parentid);
				}
				categorylist.add(category);
			}
			categorys.setCategorys(categorylist);

		} catch (Exception e) {

		}
		return categorys;
	}

	public TuanMains searchTuan(Map<String, String> parameters) {

		ArrayList<TuanMain> tuanMainlist = new ArrayList<TuanMain>();
		TuanMains tuanMains = new TuanMains();
		JSONObject resultJson;
		try {
			String result = executeGet(HttpURLEncode(Constants.TUAN_SEARCH,
					parameters));
			resultJson = new JSONObject(result);

			String status = (String) resultJson.get("status");
			if (status.equals(Constants.STATUS_NORMAL)) {
				JSONObject data = resultJson.getJSONObject("data");

				if (!data.isNull("total")) {
					tuanMains.setTotal(data.getString("total"));
				}
				if (!data.isNull("total_found")) {
					tuanMains.setTotal_found(data.getString("total_found"));
				}
				JSONArray dataArray = data.getJSONArray("datalist");
				for (int i = 0; i < dataArray.length(); i++) {
					TuanMain tuanMain = new TuanMain();
					if (!dataArray.getJSONObject(i).isNull("cityid")) {
						tuanMain.setCityid(dataArray.getJSONObject(i)
								.getString("cityid"));
					}
					if (!dataArray.getJSONObject(i).isNull("catid")) {
						tuanMain.setCatid(dataArray.getJSONObject(i).getString(
								"catid"));
					}
					if (!dataArray.getJSONObject(i).isNull("value")) {
						tuanMain.setValue(dataArray.getJSONObject(i).getString(
								"value"));
					}
					if (!dataArray.getJSONObject(i).isNull("price")) {
						tuanMain.setPrice(dataArray.getJSONObject(i).getString(
								"price"));
					}
					if (!dataArray.getJSONObject(i).isNull("rebate")) {
						tuanMain.setRebate(dataArray.getJSONObject(i)
								.getString("rebate"));
					}
					if (!dataArray.getJSONObject(i).isNull("ismajor")) {
						tuanMain.setIsmajor(dataArray.getJSONObject(i)
								.getString("ismajor"));
					}
					if (!dataArray.getJSONObject(i).isNull("startime")) {
						tuanMain.setStartime(dataArray.getJSONObject(i)
								.getString("startime"));
					}
					if (!dataArray.getJSONObject(i).isNull("endtime")) {
						tuanMain.setEndtime(dataArray.getJSONObject(i)
								.getString("endtime"));
					}
					if (!dataArray.getJSONObject(i).isNull("name")) {
						tuanMain.setName(dataArray.getJSONObject(i).getString(
								"name"));
					}
					if (!dataArray.getJSONObject(i).isNull("sitename")) {
						tuanMain.setSitename(dataArray.getJSONObject(i)
								.getString("sitename"));
					}
					if (!dataArray.getJSONObject(i).isNull("siteurl")) {
						tuanMain.setSiteurl(dataArray.getJSONObject(i)
								.getString("siteurl"));
					}
					if (!dataArray.getJSONObject(i).isNull("productid36")) {
						tuanMain.setProductid36(dataArray.getJSONObject(i)
								.getString("productid36"));
					}
					if (!dataArray.getJSONObject(i).isNull("cover")) {
						tuanMain.setCover(dataArray.getJSONObject(i).getString(
								"cover"));
					}
					if (!dataArray.getJSONObject(i).isNull("buyurl")) {
						tuanMain.setBuyurl(dataArray.getJSONObject(i)
								.getString("buyurl"));
					}
					if (!dataArray.getJSONObject(i).isNull("detailurl")) {
						tuanMain.setDetailurl(dataArray.getJSONObject(i)
								.getString("detailurl"));
					}
					if (!dataArray.getJSONObject(i).isNull("site_detail")) {
						tuanMain.setSite_detail(dataArray.getJSONObject(i)
								.getString("site_detail"));
					}
					tuanMainlist.add(tuanMain);
				}
				tuanMains.setTuanMainList(tuanMainlist);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return tuanMains;

	}

	public void getTuanKeyWords(String sid) {
		final String s_id = sid;
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				HashMap<String, String> parameters = new HashMap<String, String>();
				Message msg = new Message();
				try {
					if (s_id == null || "".equals(s_id))
						parameters.put("sid", getSessionId());
					else
						parameters.put("sid", s_id);
					String result = executeGet(HttpURLEncode(
							Constants.TUAN_KEYWORD, parameters));
					ArrayList<String> keyList = new ArrayList<String>();
					JSONArray keyArray = new JSONArray(result);
					if (keyArray != null) {
						for (int i = 0; i < keyArray.length(); i++) {
							keyList.add(keyArray.getString(i));
						}
					}
					msg.obj = keyList;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					msg.obj = null;
					e.printStackTrace();
				}
				handler.sendMessage(msg);
			}
		});
	}

	public ArrayList<TuanCity> getTuanCities(Map<String, String> parameters) {
		ArrayList<TuanCity> tuanCitylist = new ArrayList<TuanCity>();
		JSONObject resultJson;
		try {
			String result = executeGet(HttpURLEncode(Constants.TUAN_CITY,
					parameters));
			resultJson = new JSONObject(result);
			JSONObject data = resultJson.getJSONObject("data");
			Iterator<String> keys = data.keys();
			while (keys.hasNext()) {
				String key = keys.next();
				JSONObject cityObj = data.getJSONObject(key);
				TuanCity city = new TuanCity();
				if (!cityObj.isNull("cityid")) {
					city.setCityid(cityObj.getString("cityid"));
				}
				if (!cityObj.isNull("name")) {
					city.setName(cityObj.getString("name"));
				}
				if (!cityObj.isNull("firstchar")) {
					city.setFirstchar(cityObj.getString("firstchar"));
				}
				if (!cityObj.isNull("pinyin")) {
					city.setPinyin(cityObj.getString("pinyin"));
				}
				if (!cityObj.isNull("order")) {
					city.setOrder(cityObj.getString("order"));
				}
				tuanCitylist.add(city);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return tuanCitylist;

	}

	public void register(final Map<String, String> parameters) {
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				Message msg = new Message();
				try {
					String result = executeGet(HttpURLEncode(
							Constants.MEMBER_REGISTER, parameters));
					if (result == null) {
						return;
					}

					String temp = result;
					if (temp.contains("status")) {
						JSONObject jsonobj = new JSONObject(temp);
						if (((String) jsonobj.get("status")).equals("HASLOGIN")) {
							HashMap<String, String> map = new HashMap<String, String>();
							map.put("sid", parameters.get("sid"));
							boolean status = logout(map, true);
							if (status) {
								String tem = executeGet(HttpURLEncode(
										Constants.MEMBER_REGISTER, parameters));
								if (tem == null) {
									return;
								}
								int uid = Integer.parseInt(tem);
								msg.obj = uid;
							} else
								throw new Exception();
						}
					} else {
						System.out.println(result);
						int uid = Integer.parseInt(result);
						msg.obj = uid;
					}

				} catch (Exception e) {
					Bundle bundle = new Bundle();
					bundle.putBoolean(Constants.IS_ERROR, true);
					msg.setData(bundle);
				}
				handler.sendMessage(msg);
			}
		});
	}

	public void login(final Map<String, String> parameters) {
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				Message msg = new Message();
				try {
					int uid = 0;
					String result = executeGet(HttpURLEncode(
							Constants.MEMBER_LOGIN, parameters));

					System.out.println(result);

					if (result == null) {
						return;
					}
					String temp = result;
					if (temp.contains("status")) {
						JSONObject jsonobj = new JSONObject(temp);
						if (((String) jsonobj.get("status")).equals("HASLOGIN")) {
							HashMap<String, String> map = new HashMap<String, String>();
							map.put("sid", parameters.get("sid"));
							logout(map, true);
							uid = login(parameters, true);

						}
					} else {
						result = result.replace("\"", "").trim();
						uid = Integer.parseInt(result);
					}
					msg.obj = uid;
				} catch (Exception e) {
					Bundle bundle = new Bundle();
					bundle.putBoolean(Constants.IS_ERROR, true);
					msg.setData(bundle);
				}
				handler.sendMessage(msg);
			}
		});
	}

	public boolean logout(Map<String, String> parameters, boolean temp) {
		boolean logoutStatus = false;
		try {
			String result = executeGet(HttpURLEncode(Constants.MEMBER_LOGOUT,
					parameters));
			logoutStatus = true;

			System.out.println(result);
		} catch (Exception e) {

		}
		return logoutStatus;
	}

	public int login(Map<String, String> parameters, boolean temp) {
		int uid = 0;
		try {
			String result = executeGet(HttpURLEncode(Constants.MEMBER_LOGIN,
					parameters));
			if (result == null) {
				return uid;
			}
			result = result.replace("\"", "").trim();

			uid = Integer.parseInt(result);
		} catch (Exception e) {
		}
		return uid;
	}

	public void getMemberInfo(final Map<String, String> parameters) {
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				Message msg = new Message();
				msg.what = 'i';
				try {
					String result = executeGet(HttpURLEncode(
							Constants.MEMBER_INFO, parameters));
					if (result == null) {
						return;
					}
					JSONObject userJson = new JSONObject(result);
					User user = new User();
					if (!userJson.isNull("uid")) {
						user.setUid(userJson.getInt("uid"));
					}
					if (!userJson.isNull("username")) {
						user.setUsername(userJson.getString("username"));
					}
					if (!userJson.isNull("nickname")) {
						user.setNickname(userJson.getString("nickname"));
					}
					if (!userJson.isNull("email")) {
						user.setEmail(userJson.getString("email"));
					}
					if (!userJson.isNull("sex")) {
						user.setGender(String.valueOf(userJson.getInt("sex")));
					}
					if (!userJson.isNull("birthday")) {
						if (userJson.getString("birthday").length() > 1)
							user.setBirthday(userJson.getString("birthday"));
					}
					if (!userJson.isNull("avatar_url")) {
						user.setAvatar_url(userJson.getString("avatar_url"));
					}
					if (!userJson.isNull("city")) {
						JSONObject cityObj = userJson.getJSONObject("city");
						String cityid = null;
						String title = null;
						if (cityObj != null) {
							Iterator<String> it = cityObj.keys();
							if (it.hasNext()) {
								cityid = it.next();
								title = cityObj.getString(cityid);
							}
						}
						if (cityid != null && title != null) {
							user.setCityId(cityid);
							user.setCityName(title);
						}
					}
					Bundle bundle = new Bundle();
					bundle.putSerializable(Constants.USER, user);
					msg.setData(bundle);
				} catch (Exception e) {
					Bundle bundle = new Bundle();
					bundle.putBoolean(Constants.IS_ERROR, true);
					msg.setData(bundle);
				}
				handler.sendMessage(msg);
			}
		});
	}

	public User getMemberInfo(final Map<String, String> parameters, boolean temp) {
		User user;
		try {
			String result = executeGet(HttpURLEncode(Constants.MEMBER_INFO,
					parameters));
			if (result == null) {
				return null;
			}
			JSONObject userJson = new JSONObject(result);
			user = new User();
			if (!userJson.isNull("uid")) {
				user.setUid(userJson.getInt("uid"));
			}
			if (!userJson.isNull("username")) {
				user.setUsername(userJson.getString("username"));
			}
			if (!userJson.isNull("nickname")) {
				user.setNickname(userJson.getString("nickname"));
			}
			if (!userJson.isNull("email")) {
				user.setEmail(userJson.getString("email"));
			}
			if (!userJson.isNull("birthday")) {
				user.setBirthday(userJson.getString("birthday"));
			}
			if (!userJson.isNull("sex")) {
				user.setGender(String.valueOf(userJson.getInt("sex")));
			}
			if (!userJson.isNull("avatar_url")) {
				user.setAvatar_url(userJson.getString("avatar_url"));
			}

			if (!userJson.isNull("city")) {
				JSONObject cityObj = userJson.getJSONObject("city");
				String cityid = null;
				String title = null;
				if (cityObj != null) {
					Iterator<String> it = cityObj.keys();
					if (it.hasNext()) {
						cityid = it.next();
						title = cityObj.getString(cityid);
					}
				}
				if (cityid != null && title != null) {
					user.setCityId(cityid);
					user.setCityName(title);
				}
			}
		} catch (Exception e) {
			return null;
		}
		return user;

	}

	public void getMemberCity(final String sid, final String cityid) {
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				String title = null;
				String id = null;
				try {
					HashMap<String, String> parameters = new HashMap<String, String>();

					if (sid == null || "".equals(sid))
						parameters.put("sid", getSessionId());
					else
						parameters.put("sid", sid);
					parameters.put("cityid", cityid);
					String result = executeGet(HttpURLEncode(
							Constants.MEMBER_CITY, parameters));
					if (result == null) {
						title = "";
					}
					JSONObject json = new JSONObject(result);

					if (!json.isNull("title")) {
						title = json.getString("title");
					}
					if (!json.isNull("id")) {
						id = json.getString("id");
					}
				} catch (Exception e) {
					title = null;
					id = null;
				}
				Message msg = new Message();
				Bundle bundle = new Bundle();
				msg.what = 'c';
				bundle.putString("title", title);
				bundle.putString("id", id);
				msg.setData(bundle);
				handler.sendMessage(msg);
			}
		});
	}

	public List<Map<String, String>> getMemberCityList(
			Map<String, String> parameters) {
		List<Map<String, String>> cityList = null;
		try {
			String result = executeGet(HttpURLEncode(Constants.MEMBER_CITY,
					parameters));
			if (result == null) {
				return null;
			}
			JSONObject json = new JSONObject(result);
			Iterator<String> cityIdkeys = json.keys();
			cityList = new ArrayList<Map<String, String>>();
			while (cityIdkeys.hasNext()) {
				String cityId = cityIdkeys.next();
				String cityName = json.getString(cityId);
				Map<String, String> map = new HashMap<String, String>();
				map.put("id", cityId);
				map.put("title", cityName);
				cityList.add(map);
			}
		} catch (Exception e) {
			cityList = null;
		}
		return cityList;

	}

	public String uploadAvatar(String sessionId, byte[] b) {
		String result = null;
		HashMap<String, String> map = new HashMap<String, String>();
		if (sessionId == null || "".equals(sessionId))
			map.put("sid", getSessionId());
		else
			map.put("sid", sessionId);
		String urlStr = HttpURLEncode(Constants.MEMBER_AVATAR, map);
		System.out.println(urlStr);
		try {
			String boundary = "_=" + UUID.randomUUID().toString();// "----WebKitFormBoundaryAd2H9Tfw3NU6KBiS";
			String end = "\r\n";
			String hyphens = "--";

			URL url = new URL(urlStr);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setConnectTimeout(CONNECT_TIME_OUT);
			con.setReadTimeout(READ_TIME_OUT);
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 允许Input、Output，不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("connection", "keep-alive");
			con.setRequestProperty("Charset", "utf-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + boundary);
			// con.connect();
			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			StringBuffer sb = new StringBuffer();
			sb.append(hyphens);
			sb.append(boundary);
			sb.append(end);
			sb.append("Content-Disposition: form-data; name=\"avatar\"; filename=\"avatar.jpeg\""
					+ end);
			sb.append("Content-Type: image/jpeg; charset=\"utf-8\"" + end);
			sb.append(end);

			ds.write(sb.toString().getBytes());
			ByteArrayInputStream bai = new ByteArrayInputStream(b);
			byte[] bytes = new byte[1024];
			int len = 0;
			while ((len = bai.read(bytes)) != -1) {
				ds.write(bytes, 0, len);
			}
			bai.close();
			ds.write(end.getBytes());
			byte[] end_data = (hyphens + boundary + hyphens + end).getBytes();
			ds.write(end_data);
			ds.flush();

			ds.close();
			/* 关闭DataOutputStream */
			System.out.println(con.getResponseCode());
			/* 取得Response内容 */

			if (con.getResponseCode() == 200) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(con.getInputStream()));
				String line = null;
				StringBuffer sbi = new StringBuffer();
				while ((line = reader.readLine()) != null) {
					sbi.append(line);
				}
				result = sbi.toString();
			}

			if (result != null && !"".equals(result)
					&& !result.contains("status")) {
				result = result.replace("\"", "");

				if (result.startsWith("http:") && result.endsWith(".jpg")) {
					result = result.replace("\\", "");
					System.out.println(result);
				} else {
					System.out.println(result);
					result = null;

				}
			} else
				result = null;

		} catch (Exception e) {
			e.printStackTrace();
			result = null;
		}
		return result;
	}

	public void updateProfile(final Map<String, String> parameters) {
		executorService.submit(new Runnable() {

			@Override
			public void run() {
				Message msg = new Message();
				msg.what = 'p';
				try {
					String result = executeGet(HttpURLEncode(
							Constants.MEMBER_UPDATE_INFO, parameters));
					if (result.equals("true"))
						msg.arg1 = 1;
					else
						msg.arg1 = 0;
					System.out.println(result);
				} catch (Exception e) {
					msg.arg1 = -1;
				}
				handler.sendMessage(msg);

			}
		});
	}

	public void getFavorite(final Map<String, String> parameters) {

		executorService.submit(new Runnable() {

			@Override
			public void run() {
				List<Map<String, String>> list = null;
				Message msg = new Message();
				msg.what = 'f';
				try {
					String result = executeGet(HttpURLEncode(
							Constants.MEMBER_FAV, parameters));
					JSONArray favArray = new JSONArray(result);
					if (favArray != null) {
						list = new ArrayList<Map<String, String>>();
						for (int i = 0; i < favArray.length(); i++) {
							JSONObject favJson = (JSONObject) favArray.get(i);
							HashMap<String, String> map = new HashMap<String, String>();
							if (!favJson.isNull("favid")) {
								map.put("favid", favJson.getString("favid"));
							}
							if (!favJson.isNull("goodsid")) {
								map.put("goodsid", favJson.getString("goodsid"));
							}
							if (!favJson.isNull("mallid")) {
								map.put("mallid", favJson.getString("mallid"));
							}
							list.add(map);
						}
					}
					msg.obj = list;
				} catch (Exception e) {

				}
				handler.sendMessage(msg);
			}
		});
	}

	public List<Map<String, String>> getFavorite(
			final Map<String, String> parameters, boolean temp) {
		List<Map<String, String>> list = null;
		try {
			String result = executeGet(HttpURLEncode(Constants.MEMBER_FAV,
					parameters));
			JSONArray favArray = new JSONArray(result);
			if (favArray != null) {
				list = new ArrayList<Map<String, String>>();
				for (int i = 0; i < favArray.length(); i++) {
					JSONObject favJson = (JSONObject) favArray.get(i);
					HashMap<String, String> map = new HashMap<String, String>();
					if (!favJson.isNull("favid")) {
						map.put("favid", favJson.getString("favid"));
					}
					if (!favJson.isNull("goodsid")) {
						map.put("goodsid", favJson.getString("goodsid"));
					}
					if (!favJson.isNull("mallid")) {
						map.put("mallid", favJson.getString("mallid"));
					}
					list.add(map);
				}
			}
		} catch (Exception e) {
			return null;
		}
		return list;
	}

	public void addFavorite(final Map<String, String> parameters) {
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				int isSuccess = 0;
				try {
					String result = executeGet(HttpURLEncode(
							Constants.MEMBER_FAV_ADD, parameters));
					if (result.equals("\"1\""))
						isSuccess = 1;
					System.out.println(result);
				} catch (Exception e) {
					e.printStackTrace();
					isSuccess = 0;
				}
				Message msg = new Message();
				msg.arg1 = isSuccess;
				msg.what = 1;
				handler.sendMessage(msg);
			}
		});
	}

	public void delFavorite(final Map<String, String> parameters) {
		executorService.submit(new Runnable() {
			@Override
			public void run() {
				int isSuccess = 0;
				try {
					String result = executeGet(HttpURLEncode(
							Constants.MEMBER_FAV_DEL, parameters));
					if (result.equals("\"1\""))
						isSuccess = 1;
					System.out.println(result);
				} catch (Exception e) {
					e.printStackTrace();
					isSuccess = 0;
				}
				Message msg = new Message();
				msg.arg1 = isSuccess;
				msg.obj = parameters.get("autoid");
				msg.what = 2;
				handler.sendMessage(msg);
			}
		});
	}

	public boolean delFavorite(final Map<String, String> parameters,
			boolean temp) {
		boolean isSuccess = false;
		try {
			String result = executeGet(HttpURLEncode(Constants.MEMBER_FAV_DEL,
					parameters));
			if (result.equals("\"1\""))
				isSuccess = true;
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
			isSuccess = false;
		}
		return isSuccess;
	}

	public String buildSessionId() {
		// return "308781e9825a19a28e69872e52dddf6a";
		String result = "";
		String status = "";
		String sid = "";
		SystemInfo sysInfo = SystemInfoUtil.getSysInfo(this.context);
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("os", sysInfo.getOs());
		map.put("os_ver", sysInfo.getOs_ver());
		map.put("cellnum", sysInfo.getCellnum());
		String url = HttpURLEncode(Constants.SESSION_BUILD_ID, map);
		String body = "hardware=" + URLEncoder.encode(sysInfo.getHardware());
		JSONObject resultJson;
		if (!"".equals(sysInfo.getOther()) && sysInfo.getOther() != null)
			body = body + "&" + "other="
					+ URLEncoder.encode(sysInfo.getOther());
		try {
			result = executePost(url, body);
			resultJson = new JSONObject(result);
			status = (String) resultJson.get("status");
			if (status.equals(Constants.STATUS_NORMAL))
				sid = (String) resultJson.getJSONObject("data").get("sid");
			else
				Log.e(Constants.LOG_TAG_HTTP, status);
		} catch (Exception e) {
			Log.e(Constants.LOG_TAG_HTTP, e.toString());
		}
		return sid;
	}

	public String HttpURLEncode(String method, Map<String, String> parameters) {
		if (parameters == null)
			parameters = new HashMap<String, String>();

		if (parameters.containsKey("sid")) {
			if (parameters.get("sid") == null
					|| "".equals(parameters.get("sid"))) {
				parameters.put("sid", getSessionId());
			}
		}

		String tempUrl = Constants.BASE_URL + method + "?";
		parameters.put(
				"d",
				String.valueOf(new Date().getTime() / 1000
						+ Constants.EXPIRE_TIME));
		parameters.put("k", Constants.API_KEY);

		Object[] key = parameters.keySet().toArray();
		Arrays.sort(key);
		String parmStr = "";
		for (int i = 0; i < key.length; i++) {
			if (i != key.length - 1)
				parmStr = parmStr + URLEncoder.encode(key[i].toString()) + "="
						+ URLEncoder.encode(parameters.get(key[i].toString()))
						+ "&";
			else
				parmStr = parmStr + URLEncoder.encode(key[i].toString()) + "="
						+ URLEncoder.encode(parameters.get(key[i].toString()));
		}
		try {
			parmStr = new String(parmStr.getBytes(Constants.UTF_8),
					Constants.UTF_8);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String signKey = parmStr + "|" + method + "|" + Constants.API_KEY + "|"
				+ Constants.API_SECRET;
		String signStr = Encryptor.MD5Encript(signKey).substring(8, 24);
		return tempUrl + parmStr + "&_sig=" + signStr;

	}

	public String getSessionId() {
		String sid = "";
		SPResolver spr = new SPResolver(this.context, Constants.SP_SYSTEM,
				Context.MODE_PRIVATE);
		spr.OpenEditor();
		String systemId = Encryptor.MD5Encript(SystemInfoUtil.getSysInfo(
				this.context).toString());
		String tem_systemId = spr.getValue(Constants.SP_SYSTEM_ID, "");
		String tem_sessionId = spr.getValue(Constants.SP_SESSION_ID, "");
		if (!systemId.equals(tem_systemId) || "".equals(tem_sessionId)) {
			String sessionId = this.buildSessionId();
			spr.putValue(Constants.SP_SYSTEM_ID, systemId);
			spr.putValue(Constants.SP_SESSION_ID, sessionId);
			spr.commitEditor();
			spr.closeEditor();
			((MyApplication) this.context.getApplicationContext())
					.setSessionId(sessionId);
			sid = sessionId;
		} else {
			((MyApplication) this.context.getApplicationContext())
					.setSessionId(tem_sessionId);
			sid = tem_sessionId;
		}
		return sid;
	}

	public String executeGet(String url) {
		System.out.println(url);
		String result = null;
		BufferedReader reader = null;
		try {
			HttpClient client = new DefaultHttpClient();
			// 请求超时
			client.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECT_TIME_OUT);
			// 读取超时
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
					READ_TIME_OUT);
			HttpGet request = new HttpGet();
			request.setURI(new URI(url));
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {

				reader = new BufferedReader(new InputStreamReader(response
						.getEntity().getContent()));

				StringBuffer strBuffer = new StringBuffer("");
				String line = null;
				while ((line = reader.readLine()) != null) {
					strBuffer.append(line);
				}
				result = strBuffer.toString();
			} else {
				System.out.println(response.getStatusLine().getStatusCode());
			}

		} catch (Exception e) {
			e.printStackTrace();
			if (this.handler != null) {
				Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putBoolean(Constants.IS_ERROR, true);
				msg.setData(bundle);
				handler.sendMessage(msg);
				return null;
			}
		} finally {
			if (reader != null) {
				try {
					reader.close();
					reader = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	public String executePost(String url, String body) {
		String result = null;
		BufferedReader reader = null;
		try {
			HttpClient client = new DefaultHttpClient();
			// 请求超时
			client.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECT_TIME_OUT);
			// 读取超时
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
					READ_TIME_OUT);
			HttpPost request = new HttpPost();
			request.setURI(new URI(url));
			HttpEntity entity = new StringEntity(body, HTTP.UTF_8);
			request.setEntity(entity);
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				reader = new BufferedReader(new InputStreamReader(response
						.getEntity().getContent()));

				StringBuffer strBuffer = new StringBuffer("");
				String line = null;
				while ((line = reader.readLine()) != null) {
					strBuffer.append(line);
				}
				result = strBuffer.toString();
			} else {
				System.out.println(response.getStatusLine().getStatusCode());
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
					reader = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println(url);
		return result;
	}

	public void close() {
		executorService.shutdownNow();
	}

}
